package com.zodiac.alioth.common.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanMap;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class BeanMapper {

    /**
     * 映射对象
     *
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> T map(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        try {
            T ret = target.newInstance();
            BeanUtils.copyProperties(source, ret);
            return ret;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * 映射对象
     *
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> T deepMap(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        try {
            return JSON.parseObject(JSON.toJSONString(source), target);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * 映射list
     *
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> List<T> mapList(List<?> source, Class<T> target) {
        if (source == null) {
            return Collections.emptyList();
        }

        return source.stream().map((e) -> map(e, target)).collect(Collectors.toList());
    }

    public static <T> Map<String, String> beanToMap(T bean) {
        Map<String, String> map = new HashMap<>();
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.forEach((key, value) -> map.put(String.valueOf(key), (String) value));
        return map;
    }
}
